import { BASE_API } from "./baseUrl"
import { useMemberStore } from "../store"
// 存储等待重发的请求队列
let pendingRequests: Array<{
  config: any;
  resolve: (value: any) => void;
  reject: (reason?: any) => void;
}> = []
// 定义请求选项类型
interface HttpOptions extends UniApp.RequestOptions {
	contentType ?: string // 动态指定Content-Type
	showLoading ?: boolean // 是否显示加载中
}

interface ApiResponse<T = any> {
	code : number
	message : string
	data : T
}

// 移除了isToken变量，因为不再需要区分页面是否需要Token验证
const requestInterceptor = (options : HttpOptions) => {
	if (options.url && !options.url.startsWith('http')) {
		options.url = `${BASE_API}/api${options.url}`
	}

	// 设置超时时间
	options.timeout = options.timeout || 15000

	// 处理请求头
	const defaultContentType = 'application/json'
	options.header = {
		'X-Platform': 'uniapp',
		// 优先使用传入的contentType，否则用默认值
		'Content-Type': options.contentType || defaultContentType,
		...options.header
	}
	const token = uni.getStorageSync('accessToken')
	if (token) {
		options.header.Authorization = `Bearer ${token}`
	}
	const pages = getCurrentPages()

	const currentRoute = pages.length > 0 ? pages[pages.length - 1].route : ''

	// 移除了isToken的处理逻辑，因为不需要登录的页面本身就不会触发需要权限验证的接口
	const routerList = [
		'pages/citys/index',
		'pages/calendar/index',
		'pages/menu/index',
		'pages/login/index',
		'pages/home/index'
	]
	if (!token && !routerList.includes(currentRoute)) {
		uni.showToast({
			icon: 'error',
			title: '请先登录以继续操作！'
		})
		uni.navigateTo({
			url: '/pages/login/index'
		})
	}

	// 显示加载中
	if (options.showLoading !== false) {
		uni.showLoading({ title: '加载中...', mask: true })
	}

	return options
}

// 响应拦截器
const responseInterceptor = <T>(response : UniApp.RequestSuccessCallbackResult) => {
  // 隐藏加载中
  uni.hideLoading()
  
  //console.log('响应拦截器:', response.config?.url, response.statusCode, response.data)

  const res = response.data as ApiResponse<T>
  const store = useMemberStore()
  // HTTP状态码检查
  if (response.statusCode < 200 || response.statusCode >= 300) {
    // 处理401状态码，表示未授权或Token失效
    if (response.statusCode === 401) {
      const config = response.config;
	  console.log("401响应拦截器:", config)
      return new Promise(async (resolve, reject) => {
        // 判断是否是刷新Token的请求
        const isRefreshTokenRequest = config?.url?.includes('/User/refresh-token')
        
        // 如果是刷新Token请求本身返回401，直接拒绝，不加入队列
        if (isRefreshTokenRequest) {
          console.log('刷新Token请求本身返回401，直接拒绝')
          reject(response.data || '刷新Token失败')
          return
        }
        
        // 将当前请求加入等待队列
        pendingRequests.push({ config, resolve, reject })
        
        // 获取store实例
        //const store = useMemberStore()
        
        // 使用try/catch结构调用store中的刷新token方法
        try {
          console.log('开始尝试刷新Token')
          const tokenData = await store.refreshToken()
          console.log('Token刷新成功', tokenData)
          
          // token已在store中保存，这里只需使用
          const accessToken = tokenData.accessToken
          
          // 更新当前请求的Authorization头
          config.header.Authorization = `Bearer ${accessToken}`
          
          // 重发所有等待的请求
          pendingRequests.forEach(({ config, resolve }) => {
            config.header.Authorization = `Bearer ${accessToken}`
            uni.request({
              ...config,
              success: (res) => resolve(res.data),
              fail: (err) => reject(err)
            })
          })
          
          // 清空队列
          pendingRequests = []
          
          // 重发当前请求
          uni.request({
            ...config,
            success: (res) => resolve(res.data),
            fail: (err) => reject(err)
          })
        } catch (error) {
          // 增强错误日志，确保能看到完整的错误信息
          console.log('refreshToken try/catch error in http.ts:', error)
          if (error instanceof Error) {
            console.log('Error name:', error.name)
            console.log('Error message:', error.message)
            console.log('Error stack:', error.stack)
          } else {
            console.log('Non-Error object received:', typeof error, error)
          }
          
          // 通知所有等待的请求失败
          pendingRequests.forEach(({ reject }) => reject(error || '登录已过期，请重新登录'))
          // 清空队列
          pendingRequests = []
              
              // 清除token和用户信息
               // Token已在store.refreshToken的catch块中通过clearProfileSummary清除
              
              // 重定向到登录页
              const pages = getCurrentPages()
              const currentRoute = pages.length > 0 ? pages[pages.length - 1].route : ''
              if (currentRoute !== 'pages/login/index') {
                uni.showToast({
                  title: '登录已过期，请重新登录',
                  icon: 'none',
                  duration: 2000
                })
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/pages/login/index?redirect=' + encodeURIComponent(currentRoute)
                  })
                }, 1000)
              }
              
              // 拒绝当前请求，传递原始错误信息
              console.log('拒绝当前请求，错误信息:', error)
              reject(error)
            }
        
      })
    } else {
		console.log('非401错误状态码:', response.statusCode, response.data)
      console.log('响应拦截器002:', response, response.statusCode, response.data)
      // 判断是否是刷新Token的请求
      const isRefreshTokenRequest = response.config?.url?.includes('/User/refresh-token')
      
      // 如果是刷新Token请求，不显示Toast，直接拒绝
      if (isRefreshTokenRequest) {
        console.log('刷新Token请求返回非401错误:', response.statusCode, response.data)
        // 创建包含更多信息的错误对象
        const error = new Error(`刷新Token失败: ${response.statusCode}`);
        // @ts-ignore 添加额外信息
        error.response = response;
        error.data = res;
        return Promise.reject(error)
      }
      
      // 其他请求的错误处理
      uni.showToast({ title: res?.message || `网络错误: ${response.statusCode}`, icon: 'none' })
      // 创建包含更多信息的错误对象
      const error = new Error(`HTTP错误: ${response.statusCode}`);
      // @ts-ignore 添加额外信息
      error.response = response;
      error.data = res;
      return Promise.reject(error)
    }
  }
  
  return res
}

// 错误处理
const errorHandler = (err : any) => {
	console.log('请求失败 errorHandler:', err)
	uni.hideLoading()
	uni.showToast({ title: '请求失败，请稍后重试', icon: 'none' })
	// 确保错误被正确传递，不要吞掉错误
	return Promise.reject(err)
}

// 注册拦截器
uni.addInterceptor('request', {
	invoke: requestInterceptor,
	success: responseInterceptor,
	fail: errorHandler
})

export const http = <T = any>(options : HttpOptions) : Promise<T> => {
	console.log('发起请求:', options.url, options)
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {
				console.log('请求成功:', options.url, res.statusCode, res.data)
				resolve(res.data as T)
			},
			fail: (err) => {
				console.log('请求失败 http函数:', options.url, err)
				// 确保错误被正确传递
				reject(err)
			}
		})
	})
}

export const request = {
	get: <T = any>(url : string, data ?: any, options ?: Omit<HttpOptions, 'url' | 'method' | 'data'>) => {
		return http<T>({ method: 'GET', url, data, ...options })
	},
	post: <T = any>(url : string, data ?: any, options ?: Omit<HttpOptions, 'url' | 'method' | 'data'>) => {
		return http<T>({ method: 'POST', url, data, ...options })
	}
}